﻿using BLL;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Web;

namespace Thksoft.Module.StatisticalReport
{
    /// <summary>
    /// api 的摘要说明
    /// </summary>
    public class api : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.RequestType != "POST")
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("欢迎使用！");
                return;
            }
            string returnStr = "";
            string jsonStr = null;
            {
                var Request = context.Request;
                var Response = context.Response;
                switch (Request.Params.Get("Type"))
                {
                    case "GET_BANK_MSG":
                        {
                            #region MyRegion

                            //读取上传流
                            using (var stream = new StreamReader(context.Request.InputStream))
                            {
                                jsonStr = stream.ReadToEnd();
                            }

                            var jdata = JObject.Parse(jsonStr);
                            var userId = jdata["UserId"].ToObject<int?>();
                            var skip = jdata["Skip"].ToObject<int?>();
                            var take = jdata["Take"].ToObject<int?>();
                            returnStr = Success();

                            #endregion MyRegion

                            break;
                        }
                    case "UPLOAD_FILE":
                        {
                            #region 上传文件

                            try
                            {
                                context.Request.ContentEncoding = System.Text.Encoding.UTF8;
                                var file = context.Request.Files[0];
                                var dic = "/UpLoad/Temporary/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
                                if (!System.IO.Directory.Exists(context.Request.MapPath(dic)))
                                {
                                    System.IO.Directory.CreateDirectory(context.Request.MapPath(dic));
                                }
                                var filename = dic + Guid.NewGuid() + System.IO.Path.GetExtension(file.FileName);
                                file.SaveAs(context.Request.MapPath(filename));
                                context.Response.ContentType = "application/json";
                                returnStr = JsonConvert.SerializeObject(new { Type = 1, Data = filename });
                            }
                            catch (Exception)
                            {
                                context.Response.ContentType = "application/json";
                                returnStr = JsonConvert.SerializeObject(new { Type = 0 });
                            }

                            #endregion 上传文件

                            break;
                        }
                    default:
                        {
                            #region MyRegion

                            try
                            {
                                //读取上传流
                                using (var stream = new StreamReader(context.Request.InputStream))
                                {
                                    jsonStr = stream.ReadToEnd();
                                }

                                var jdata = JObject.Parse(jsonStr);
                                var type = jdata.Value<string>("Type");
                                switch (type)
                                {
                                    case "Year":
                                        {
                                            #region 代码块

                                            var id = jdata["Data"]["ID"].ToObject<string>();
                                            var planYearApplyBLL = new QX_PLANYEARAPPLYBLL();
                                            var entity = planYearApplyBLL.Find(Convert.ToDecimal(id));

                                            //查询年 所有交易记录
                                            var sql = @"select nvl(a.n_month,0) n_month,
       nvl(into_amount,0) into_amount,
       nvl(into_use,0) into_use,
       nvl(out_amount,0) out_amount,
       nvl(out_use,0) out_use
  from (select t.n_month,
               sum(decode(d.n_type2, 1, d.n_amount, 0)) into_amount,
               sum(decode(d.n_type2, 2, d.n_amount, 0)) out_amount
          from qs_planmonthapply t, qs_planmonth_detail d
         where t.n_business_state = 2
           and t.N_YEARAPP_ID = {0}
           and t.n_monthapp_id = d.n_monthapp_id
           and d.n_type = 0
         group by t.n_month) a
  left join (select w.n_month,
                    sum(decode(d.n_type2, 1, d.N_USEAMOUNT, 0)) into_use,
                    sum(decode(d.n_type2, 2, d.N_USEAMOUNT, 0)) out_use
               from qs_planweekapply w, qs_planweek_detail d
              where w.N_YEARAPP_ID = {0}
                and w.n_business_state = 2
                and w.n_weekapp_id = d.n_weekapp_id
                and d.n_type = 0
              group by w.n_month) b
    on (a.n_month = b.n_month)
 order by a.n_month ";
                                            sql = string.Format(sql, entity.N_YEARAPP_ID);
                                            var dt = planYearApplyBLL.Query(sql);
                                            returnStr = JsonConvert.SerializeObject(new { Success = true, Data = dt, Entity = entity });

                                            #endregion 代码块
                                        }
                                        break;

                                    case "Month":
                                        {
                                            #region 代码块

                                            var id = jdata["Data"]["ID"].ToObject<string>();
                                            var planMonthApplyBLL = new QS_PLANMONTHAPPLYBLL();
                                            var entity = planMonthApplyBLL.Find(Convert.ToDecimal(id));
                                            //查询年 所有交易记录
                                            var sql = @"select nvl(t.n_week,0) n_week,
       nvl(sum(decode(d.n_type2, 1, d.N_AMOUNT, 0)),0) into_amount,
       nvl(sum(decode(d.n_type2, 1, d.N_USEAMOUNT, 0)),0) into_use,
       nvl(sum(decode(d.n_type2, 2, d.N_AMOUNT, 0)),0) out_amount,
       nvl(sum(decode(d.n_type2, 2, d.N_USEAMOUNT,0)),0) out_use
  from qs_planweekapply t, qs_planweek_detail d
 where t.n_business_id <> 0
   and t.n_monthapp_id = {0}
   and t.n_business_state = 2
   and t.n_weekapp_id = d.n_weekapp_id
   and d.n_type = 0
 group by t.n_week
 order by n_week
";
                                            sql = string.Format(sql, entity.N_MONTHAPP_ID);
                                            var dt = planMonthApplyBLL.Query(sql);
                                            returnStr = JsonConvert.SerializeObject(new { Success = true, Data = dt, Entity = entity });

                                            #endregion 代码块
                                        }
                                        break;

                                    case "WEEK_TABLE":
                                        {
                                            #region 代码块

                                            var id = jdata["Data"]["ID"].ToObject<string>();
                                            var planWeekApplyBLL = new QS_PLANWEEKAPPLYBLL();
                                            var entity = planWeekApplyBLL.Find(Convert.ToDecimal(id));
                                            var sql = @"select nvl(t.n_amount,0) n_amount, nvl(t.n_useamount,0) n_useamount, nvl(t.c_proname,0) c_proname
  from qs_planweek_detail t
 where t.n_weekapp_id = {0}
   and t.N_TYPE = 2
   and (t.n_amount <> 0 or n_useamount <> 0)
 order by t.n_weekdetail_id ";

                                            sql = string.Format(sql, entity.N_WEEKAPP_ID);
                                            var dt = planWeekApplyBLL.Query(sql);

                                            returnStr = JsonConvert.SerializeObject(new { Success = true, Data = dt, Entity = entity });

                                            #endregion 代码块
                                        }
                                        break;

                                    case "Print":
                                        {
                                            var html = jdata["Data"].ToObject<string>();
                                            var key = Guid.NewGuid().ToString();
                                            context.Session[key] = html;
                                            returnStr = JsonConvert.SerializeObject(new { Success = true, Data = key, Msg = "生成成功" });
                                        }
                                        break;

                                    default:
                                        break;
                                }
                            }
                            catch (Exception)
                            {
                                returnStr = JsonConvert.SerializeObject(new { Success = false, Msg = "发生错误" });
                            }

                            #endregion MyRegion

                            break;
                        }
                }
            }
            context.Response.ContentType = "application/json";
            context.Response.Write(returnStr);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string Reson(string msg, int type, object data)
        {
            var jObj = new JObject();
            jObj["Msg"] = msg;
            jObj["Type"] = type;
            if (data != null)
            {
                jObj["Data"] = JToken.FromObject(data);
            }
            return jObj.ToString();
        }

        private string Success(object data = null)
        {
            return Reson("获取成功", 1, data);
        }

        private string Erro(string msg = "接口异常")
        {
            return Reson(msg, 0, null);
        }
    }

    public class serie
    {
        public string name { get; set; }
        public string type { get; set; }
        public string stack { get; set; }
        public decimal[] data { get; set; }
    }

    public class WEEK_TABLE_MODEL
    {
        /// <summary>
        /// 交易ID
        /// </summary>
        public int ID { get; set; }

        /// <summary>
        /// 备注
        /// </summary>
        public string REMARK { get; set; }

        /// <summary>
        /// 交易流水号
        /// </summary>
        public string ACCOUNT_FLOW { get; set; }

        /// <summary>
        /// 对方名称
        /// </summary>
        public string ACCOUNT_NAME { get; set; }

        /// <summary>
        /// 对方账号
        /// </summary>
        public string ACCOUNT { get; set; }

        /// <summary>
        /// 发生额
        /// </summary>
        public decimal MONEY { get; set; }

        /// <summary>
        /// 银行流水产生时间
        /// </summary>
        public DateTime SCOP_DATE { get; set; }

        /// <summary>
        /// 借贷标志 false-借 转出 ,True-贷 转入
        /// </summary>
        public bool FLAG { get; set; }

        /// <summary>
        /// 银行ID
        /// </summary>
        public int BANK_ID { get; set; }

        /// <summary>
        /// 银行名称
        /// </summary>
        public string BANK_NAME { get; set; }
    }
}